package SmartFleet.station;

import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

import linker.ClientLinker;
import linker.exception.CanNotCreateSocketException;
import linker.exception.CanNotWriteObjectException;
import smartfleet.communication.smartfleetobjects.GeneralInfo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class SendFlightService extends Service {
	
	private static SmartFleetStation	MAIN_ACTIVITY;
	
	private Timer						timer	= new Timer();
	
	private void sendFlight() {

		this.timer.scheduleAtFixedRate(new TimerTask() {
			
			@Override
			public void run() {

				if (!MAIN_ACTIVITY.isBooking() && !MAIN_ACTIVITY.getMyStation().getFlightQueue().isEmpty() && !MAIN_ACTIVITY.getMyStation().getMyCars().isEmpty()) {
					
					Flight flight = MAIN_ACTIVITY.getMyStation().getFlightQueue().get(0);
					Iterator iterator = MAIN_ACTIVITY.getMyStation().getMyCars().keySet().iterator();
					int key = (Integer) iterator.next();
					GeneralInfo info = MAIN_ACTIVITY.getMyStation().getMyCars().get(key);
					
					String ip = info.getIp();
					int port = info.getPort();
					
					try {
						ClientLinker client = new ClientLinker(ip, port);
						
						client.writeObject(flight);
						MAIN_ACTIVITY.getMyStation().getFlightQueue().remove(0);
						MAIN_ACTIVITY.getMyStation().getMyCars().remove(key);
						
					} catch (CanNotCreateSocketException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (CanNotWriteObjectException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
		}, 0, 1000);
		
		;
	}
	
	private void stopservice() {

		if (this.timer != null)
			this.timer.cancel();
		
	}
	
	@Override
	public IBinder onBind(Intent intent) {

		return null;
	}
	
	@Override
	public void onCreate() {

		super.onCreate();
		sendFlight();
	}
	
	@Override
	public void onDestroy() {

		super.onDestroy();
		stopservice();
	}
	
	public static void setMainActivity(SmartFleetStation activity) {

		MAIN_ACTIVITY = activity;
	}
}